import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart';


final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

Future<void> initializeNotifications() async {
  initializeTimeZones();

  const AndroidInitializationSettings initializationSettingsAndroid =
  AndroidInitializationSettings("@mipmap/ic_launcher");

  const InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid);

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}

void localNotify(String title,String body) async {
  const AndroidNotificationDetails androidPlatformChannelSpecifics =
  AndroidNotificationDetails(
    'channel_id',
    'channel_name',
    importance: Importance.max,
    priority: Priority.high,
  );
  const NotificationDetails platformChannelSpecifics =
  NotificationDetails(android: androidPlatformChannelSpecifics);

  await flutterLocalNotificationsPlugin.show(11, title, body, platformChannelSpecifics);
}

void scheduleNotify(String title,String body,int minute) {
  const AndroidNotificationDetails androidPlatformChannelSpecifics =
  AndroidNotificationDetails(
    'channel_id_schedule',
    'channel_name_schedule',
    importance: Importance.max,
    priority: Priority.high,
  );
  const NotificationDetails platformChannelSpecifics =
  NotificationDetails(android: androidPlatformChannelSpecifics);

  var now = DateTime.now();
  var nextTime = now.add(Duration(minutes: 1));


  flutterLocalNotificationsPlugin.zonedSchedule(11, title, body,
      _nextInstanceOfTime(nextTime),
      platformChannelSpecifics,
      androidScheduleMode: AndroidScheduleMode.exact
  );
}

tz.TZDateTime _nextInstanceOfTime(DateTime scheduledTime) {
  //获取手机当前时区的时间
  tz.TZDateTime now = tz.TZDateTime.now(tz.getLocation("America/Detroit"));

  tz.TZDateTime scheduledDate = tz.TZDateTime(
    tz.getLocation("America/Detroit"),
    now.year,
    now.month,
    now.day,
    scheduledTime.hour,
    scheduledTime.minute,
  );

  if (scheduledDate.isBefore(now)) {
    scheduledDate = scheduledDate.add(const Duration(days:1));
  }
  return scheduledDate;
}
